#coding=utf-8
from uliweb import expose

#可以省略直接引用
from uliweb import request,functions,json
from sqlalchemy import and_,or_,desc,asc

def __begin__():
    """
    用户验证
    """
    from uliweb import functions
    return functions.require_login()

@expose('/myuserpost')
class PostData(object):

    
    def __init__(self):
        from uliweb.orm import get_model
        self.usermodel = get_model('user')
        self.usergroupmodel = get_model('usergroup')
  
    def user(self):
        """        
        所有用户的数据,用于bootstrap-table
        """
        
        #得到偏移量
        pageIndex= request.GET.get('offset',0)
        #得到查询个数
        pageSize = request.GET.get('limit',20)
        
        #得到搜索字段
        search_key = request.GET.get('search')
            
        #得到排序字段
        sort = request.GET.get('sort','id')
        #得到排序规则
        order_by_type = request.GET.get('order','asc')
        
        #使用sqlchemy自带asc方法，uliweb版本  self.usermodel.c['id'].asc()或self.usermodel.c.id.asc()
        if order_by_type == 'asc':
            #升序
            #order_by = asc('id')
            order_by = self.usermodel.c[sort].asc()
        else:
            #降序
            #order_by = desc ('id')
            order_by = self.usermodel.c[sort].desc()
        
        data = {}
        data['rows'] = []

        #用于判断是用户管理还是注册锁定管理
        locked = request.GET.get('locked','0')
        
        #列出锁定用户
        if locked == "1":
            
            #没有搜索操作
            if search_key=="" or search_key == None:
                #得到总数
                data['total'] = self.usermodel.filter(self.usermodel.c.locked==1).count()
        
                #分页获取数据
                ormdata = self.usermodel.filter(self.usermodel.c.locked==1).order_by(order_by).limit(pageSize).offset(pageIndex)
            else:
                #拼接搜索
                key = or_(self.usermodel.c.username.like('%%' +search_key + '%%'),
                          self.usermodel.c.nickname.like('%%' +search_key + '%%'),
                          self.usermodel.c.email.like('%%' +search_key + '%%'),
                          self.usermodel.c.mobile.like('%%' +search_key + '%%')
                          )
        
                #获取所有记录
                data['total'] = self.usermodel.filter(key).filter(self.usermodel.c.locked==1).count()
        
                ormdata = self.usermodel.filter(key).filter(self.usermodel.c.locked==1).order_by(order_by).limit(pageSize).offset(pageIndex)
                
        elif locked == "0":

            #没有搜索操作
            if search_key=="" or search_key == None:
                #得到总数
                data['total'] = self.usermodel.all().count()
                
                #分页获取数据
                ormdata = self.usermodel.all().order_by(order_by).limit(pageSize).offset(pageIndex)
            else:
                #拼接搜索
                key = or_(self.usermodel.c.username.like('%%' +search_key + '%%'),
                          self.usermodel.c.nickname.like('%%' +search_key + '%%'),
                          self.usermodel.c.email.like('%%' +search_key + '%%'),
                          self.usermodel.c.mobile.like('%%' +search_key + '%%')
                          )
        
                #获取所有记录
                data['total'] = self.usermodel.filter(key).count()
    
                ormdata = self.usermodel.filter(key).order_by(order_by).limit(pageSize).offset(pageIndex)
        else:
            #数据非法
            data['rows'] = {}
            return json(data)


        for i in ormdata:
                
            #1 超级管理员 0 普通用户
            if i.is_superuser:
                is_superuser = '是'
            else:
                is_superuser = '否' 
                
            # 1删除 0 正常
            if i.deleted:
                deleted = '删除'
            else:
                deleted = '正常'

            # 1锁定 0 激活
            if i.locked:
                locked = '锁定'
            else:
                locked = '激活'
            
            data['rows'].append({"id":i.id,
                         "username":i.username,
                         "nickname":i.nickname,
                         "email":i.email,
                         "is_superuser":is_superuser,
                         "mobile":i.mobile,
                         "deleted":deleted,
                         "locked":locked,
                         "date_join":i.date_join
                         })
        #返回json串
        return json(data)


    def usergroup(self):
        """        
        所有用户的数据,用于bootstrap-table
        """

        #得到偏移量
        pageIndex= request.GET.get('offset',0)
        #得到查询个数
        pageSize = request.GET.get('limit',20)

        #得到搜索字段
        search_key = request.GET.get('search')

        #得到排序字段
        sort = request.GET.get('sort','id')
        #得到排序规则
        order_by_type = request.GET.get('order','asc')

        #使用sqlchemy自带asc方法，uliweb版本  self.usermodel.c['id'].asc()或self.usermodel.c.id.asc()
        if order_by_type == 'asc':
            #升序
            #order_by = asc('id')
            order_by = self.usergroupmodel.c[sort].asc()
        else:
            #降序
            #order_by = desc ('id')
            order_by = self.usergroupmodel.c[sort].desc()

        data = {}
        data['rows'] = []


        #得到总数
        data['total'] = self.usergroupmodel.all().count()

        #分页获取数据
        ormdata = self.usergroupmodel.all().order_by(order_by).limit(pageSize).offset(pageIndex)

        for i in ormdata:

            users = []
            
            # 1删除 0 正常
            if i.deleted:
                deleted = '删除'
            else:
                deleted = '正常'

            for j in i.users:
                users.append(j.nickname)

            data['rows'].append({"id":i.id,
                                 "name":i.name,
                                 "deleted":deleted,
                                 "created_time":i.created_time,
                                 "users":",".join(users)
                                 })
        #返回json串
        return json(data)
##############################################################################################    
    
    def userinfo(self):
        """
        获取非超级管理员用户，提供给combobox
        """
        data = []
        #找出非管理员，并且状态不是删除和锁定的用户
        orm_data = {'data':self.usermodel.filter(
            self.usermodel.c.is_superuser == 0
            ).filter(self.usermodel.c.deleted ==0).filter(self.usermodel.c.locked ==0).order_by(self.usermodel.c.id)}
        
        for i in orm_data['data']:
                
            data.append({"id":i.id,
                         "username":i.username,
                         "nickname":i.nickname
                        })

        #返回json串
        return json(data)
